<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores'
import { userUpdateInfoService } from '@/api/user'

const loading = ref(false)
const form = ref()
// 用户信息的数据，只需要获取第一次，所以不需要响应式，可以结构
const {
  user: { id, username, nickname, email, user_pic },
  getUserInfo
} = useUserStore()

const formModel = ref({
  id,
  username, // 假设用户名为 admin，禁用不可更改
  nickname,
  email,
  user_pic
})

const rules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      pattern: /^\S{2,10}$/,
      message: '长度在 2 到 10 个非空字符',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ]
}

const submitForm = async () => {
  loading.value = true
  // 表单预校验
  await form.value.validate()
  await userUpdateInfoService(formModel.value)
  loading.value = false
  ElMessage.success('修改成功')
  // 重新渲染数据
  getUserInfo()
}
</script>
<template>
  <page-container title="基本资料">
    <el-row>
      <el-col :span="12">
        <el-form
          v-loading="loading"
          element-loading-text="拼命加载中..."
          ref="form"
          :model="formModel"
          :rules="rules"
          label-width="120px"
          size="large"
          class="demo-ruleForm"
        >
          <el-form-item label="登录名称">
            <el-input v-model="formModel.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formModel.nickname"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="formModel.email"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('form')"
              >提交修改</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </page-container>
</template>
